using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using BIUtilities.Publish.PasDataObjects;

namespace BIUtilities.Publish
{
    /// <summary>
    /// Class to hold the contents of a report details, and can be passed 
    /// to other deployment items who need information on a PAS report.
    /// </summary>
    public struct PasReportDetails
    {
        /// <summary>
        /// First and most outer level where a report is located
        /// </summary>
        public Library Library;
        /// <summary>
        /// The book within the library, which contains the report
        /// </summary>
        public Book Book;
        /// <summary>
        /// The Report page, known as a BookElement to PAS
        /// </summary>
        public Page BookElement;
        /// <summary>
        /// The string path which represents a '\' delimited path of names to a report.
        /// </summary>
        public string PagePath;
    }

    /// <summary>
    /// Deployment utility which uses Proclarity Analytic Server Webservice to lookup information about reports
    /// </summary>
    public class ProclarityAnalyticServerDeployUtility
    {
        private PasWebService.PStore _targetWebservice = null;
        private string _matchOnLibrary;
        private string _matchOnBook;
        private string _matchOnBookElement;
        private List<PasReportDetails> _reportList = new List<PasReportDetails>();

        /// <summary>
        /// Sets the target webservice to update for PAS
        /// </summary>
        public string TargetWebserviceUrl
        {
            get { return _targetWebservice.Url; }
            set {
                _targetWebservice = new PasWebService.PStore(value + "/pstore.asp");
                _targetWebservice.Url = value + "/pstore.asp";
                System.Diagnostics.Trace.WriteLine("PAS Webservice: " + _targetWebservice.Url);
                _targetWebservice.UseDefaultCredentials = true;
            }
        }

        /// <summary>
        /// This class will match any report which is within the matching library name
        /// </summary>
        public string MatchOnLibrary
        {
            get { return _matchOnLibrary; }
            set { _matchOnLibrary = value.ToUpper(); }
        }

        /// <summary>
        /// This class will match any report which is within the matching bool name (optional)
        /// </summary>
        public string MatchOnBook
        {
            get { return _matchOnBook; }
            set { _matchOnBook = value.ToUpper(); }
        }

        /// <summary>
        /// This class will match any report which is the matching page name (optional)
        /// </summary>
        public string MatchOnPage
        {
            get { return _matchOnBookElement; }
            set { _matchOnBookElement = value.ToUpper(); }
        }

        /// <summary>
        /// Using the match values which may be entered, the affected PAS items are loaded once and stored in memory for transformations.
        /// </summary>
        public void LoadPasMatchedItems()
        {
            XmlElement xml = _targetWebservice.GetLibraries();
            foreach (XmlNode node in xml.ChildNodes)
            {
                XmlSerializer deSerializeLibrary = new XmlSerializer(typeof(PasDataObjects.Library));
                System.IO.TextReader readerLibrary = new System.IO.StringReader(node.OuterXml);
                PasDataObjects.Library library = (PasDataObjects.Library)deSerializeLibrary.Deserialize(readerLibrary);

                if (library.Caption.ToUpper() == _matchOnLibrary)
                {
                    LoadPasMatchedBooks(library);
                }
            }
        }

        /// <summary>
        /// Load all books of a library according to matched values set in object
        /// </summary>
        /// <param name="library"></param>
        private void LoadPasMatchedBooks(Library library)
        {
            XmlElement bookListXml = _targetWebservice.GetBooks(library.ID.ToString("B"), "Briefing Book");
            foreach (XmlNode bookNode in bookListXml.ChildNodes)
            {
                XmlSerializer deSerializeBook = new XmlSerializer(typeof(PasDataObjects.Book));
                System.IO.TextReader readerBook = new System.IO.StringReader(bookNode.OuterXml);
                PasDataObjects.Book book = (PasDataObjects.Book)deSerializeBook.Deserialize(readerBook);

                if ((_matchOnBook.Length == 0) || (_matchOnBook == book.Caption.ToUpper()))
                {
                    LoadPasMatchedBookElements(library, book);
                }
            }
        }

        /// <summary>
        /// Load all pages of a book according to matched values set in object
        /// </summary>
        /// <param name="library"></param>
        /// <param name="book"></param>
        private void LoadPasMatchedBookElements(Library library, Book book)
        {
            XmlElement bookElementListXml = _targetWebservice.GetBookElements(book.ID.ToString("B"), "");
            LoadPasMatchedElementsCollection(library, book, bookElementListXml);
        }

        /// <summary>
        /// Recursive function to dig deep into the folder structure.
        /// </summary>
        /// <param name="library"></param>
        /// <param name="book"></param>
        /// <param name="bookElementListXml"></param>
        private void LoadPasMatchedElementsCollection(Library library, Book book, XmlElement bookElementListXml)
        {
            foreach (XmlNode bookElementNode in bookElementListXml.ChildNodes)
            {
                // Make sure we only process Pages, do not include folders.
                if (bookElementNode.Name == "Page")
                {
                    XmlSerializer deSerializeBookElement = new XmlSerializer(typeof(PasDataObjects.Page));
                    System.IO.TextReader readerBookElement = new System.IO.StringReader(bookElementNode.OuterXml);
                    PasDataObjects.Page bookElement = (PasDataObjects.Page)deSerializeBookElement.Deserialize(readerBookElement);

                    if ((_matchOnBookElement.Length == 0) || (_matchOnBookElement == bookElement.Caption.ToUpper()))
                    {
                        PasReportDetails reportDetails = new PasReportDetails();
                        reportDetails.Library = library;
                        reportDetails.Book = book;
                        reportDetails.BookElement = bookElement;
                        reportDetails.PagePath = library.Caption + "\\" + book.Caption + "\\" + bookElement.Caption;
                        _reportList.Add(reportDetails);
                    }
                }
                else if (bookElementNode.Name == "Folder")
                {
                    XmlSerializer deSerializeBookElement = new XmlSerializer(typeof(PasDataObjects.Folder));
                    System.IO.TextReader readerBookElement = new System.IO.StringReader(bookElementNode.OuterXml);
                    PasDataObjects.Folder bookElement = (PasDataObjects.Folder)deSerializeBookElement.Deserialize(readerBookElement);

                    // Recursively load the folders and pages underneath this.
                    XmlElement bookElementChildListXml = _targetWebservice.GetBookElements(book.ID.ToString("B"), bookElement.ID.ToString("B"));
                    LoadPasMatchedElementsCollection(library, book, bookElementChildListXml);
                }
            }
        }

        /// <summary>
        /// Do a search within the 'matched' entries loaded for a given pas report given a direct page path to the report.
        /// </summary>
        /// <param name="pagePath"></param>
        /// <param name="loadedReportDetails"></param>
        /// <returns></returns>
        public bool FindReport(string pagePath, out PasReportDetails loadedReportDetails)
        {
            foreach (PasReportDetails details in _reportList)
            {
                if (details.PagePath.ToUpper() == pagePath.ToUpper())
                {
                    loadedReportDetails = details;
                    return true;
                }
            }
            loadedReportDetails = new PasReportDetails();
            return false;
        }


        /// <summary>
        /// Update the mathed reports' datasource set and stored within pas reports
        /// </summary>
        /// <param name="originalServer"></param>
        /// <param name="newServer"></param>
        public void UpdateDataSource(string originalServer, string newServer)
        {
            foreach (PasReportDetails details in _reportList)
            {
                if (details.BookElement.ServerName.ToUpper() == originalServer.ToUpper())
                {
                    details.BookElement.ServerName = newServer;
                }
            }
        }

        /// <summary>
        /// Persist the changed PAS items to the PAS target webservice.
        /// </summary>
        public void PersistPasMatchedItems()
        {
            foreach (PasReportDetails details in _reportList)
            {
                string result = _targetWebservice.EditBookElement(
                    details.BookElement.ID.ToString("B"), details.BookElement.Caption, details.BookElement.Description,
                    details.BookElement.ProviderName.ToString("B"), details.BookElement.ProviderCaption,
                    details.BookElement.ServerName, details.BookElement.LocalServerName, details.BookElement.CatalogName,
                    details.BookElement.CubeName, details.BookElement.CubeCaption, details.BookElement.SchemaName);
            }
        }
    }
}
